<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门店名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button 
        type="primary" 
        icon="el-icon-search" 
        size="mini"
       @click="handleQuery"
       v-hasPermi="['business:memCardDetailed:query']"
        >搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
       v-hasPermi="['business:memCardDetailed:edit']"
        >修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
       <el-table-column label="序号" align="center" prop="storeName" />
       <el-table-column label="会员卡编号" align="center" prop="phoneNumber" width="120"/>
       <el-table-column label="适用区域" align="center" prop="regionName" />
       <el-table-column label="归属门店" align="center" prop="detail" />
       <el-table-column label="客户姓名" align="center" prop="longitude" />
       <el-table-column label="电话" align="center" prop="detail" />
       <el-table-column label="会员卡规则名称" align="center" prop="longitude" />
       <el-table-column label="天数" align="center" prop="detail" />
       <el-table-column label="价格" align="center" prop="longitude" />
       <el-table-column label="推荐人" align="center" prop="detail" />
       <el-table-column label="推荐人电话" align="center" prop="longitude" />
       <el-table-column label="购买时间 " align="center" prop="intro" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"  width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:memCardDetailed:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:memCardDetailed:del']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal='false'>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="附加商品名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入包间名称" style="width: 222px;"/>
        </el-form-item>
  
      <el-form-item label="区域" prop="regionId">
          <el-select clearable v-model="form.regionId" @change='changeRegion'>
					<el-option v-for="(item,index) of region" :key="index" :label="item.value" :value="item.key">{{item.value}}</el-option>
				</el-select>
      </el-form-item>
      <el-form-item label="适用门店" prop="regionId">
          <el-select clearable v-model="form.regionId" @change='changeRegion'>
					<el-option v-for="(item,index) of region" :key="index" :label="item.value" :value="item.key">{{item.value}}</el-option>
				</el-select>
      </el-form-item>
        <el-form-item label="门店原价" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入门店原价" style="width: 222px;"/>
        </el-form-item>
        <el-form-item label="会员价" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入会员价" style="width: 222px;"/>
        </el-form-item>
        <el-form-item label="提成金额" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入提成金额" style="width: 222px;"/>
        </el-form-item>
        <el-form-item label="上架" prop="regionId">
          <el-select clearable v-model="form.regionId" >
					<el-option v-for="(item,index) of region" :key="index" :label="item.value" :value="item.key">{{item.value}}</el-option>
				</el-select>
      </el-form-item>
      <el-form-item label="排序" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入排序" style="width: 222px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { listStore, getStore, delStore, addStore, updateStore,listChina,listResetPwd,listregion } from "@/api/system/store";

export default {
  name: "Store",
  data() {
    return {
      map: null,
      local: null,
      mk: null,
      latitude: '',
      longitude: '',
      keyWords: '',
      result: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      options:[],
      List: [
				{
					key: 1,
					value: '营业中'
				},
				{
					key: 2,
					value: '未营业'
				},
			],
      region:[],
    };
  },
  created() {
    this.getList();
    this.listChina()
    this.listregion()
  },
  mounted(){
    this.initMap()
  },
  methods: {
    listregion(){
      listregion().then(res=>{
          this.region = res.data.map(rItem => {
            return {
              key: rItem.id,
              value: rItem.regionName,
            }
        })
      })
    },
    changeRegion(value) {
      const selectedOption = this.region.find(item => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      this.form.regionName=selectedValue
    },
    initMap(){
      this.map = new BMap.Map('map')
      let point = new BMap.Point(116.404, 39.915)
      this.map.centerAndZoom(point, 12)
      this.map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
      this.map.addControl(new BMap.NavigationControl())
    },
       // 点击定位-定位到当前位置
    fixedPos() {
        const _this = this
        const geolocation = new BMap.Geolocation()
        this.confirmLoading = true
        geolocation.getCurrentPosition(function(r) {
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            _this.handleMarker(_this, r.point)
            let myGeo = new BMap.Geocoder()
            myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), function(result) {
              _this.confirmLoading = false
              if (result) {
                _this.latitude = result.point.lat
                _this.longitude =  result.point.lng
              }
            })
          } else {
            _this.$message.error('failed' + this.getStatus())
          }
        })
    },
    // 搜索地址
    setPlace() {
      this.local = new BMap.LocalSearch(this.map, {
        onSearchComplete: this.searchPlace
      })
      this.local.search(this.form.detail)
    },
    searchPlace() {
      if (this.local.getResults() != undefined) {
        this.map.clearOverlays() //清除地图上所有覆盖物
        if (this.local.getResults().getPoi(0)) {
          let point = this.local.getResults().getPoi(0).point //获取第一个智能搜索的结果
          this.map.centerAndZoom(point, 18)
          this.handleMarker(this, point)
          console.log('经度：'+ point.lng + '--' + '纬度' + point.lat)
          this.form.longitude=point.lng
          this.form.latitude=point.lat
          this.latitude = point.lat
          this.longitude =  point.lng
        } else {
          this.$message.error('未匹配到地点!')
        }
      } else {
        this.$message.error('未找到搜索结果!')
      }
    },
    // 设置标注
    handleMarker(obj, point) {
      obj.mk = new BMap.Marker(point)
      obj.map.addOverlay(obj.mk)
      obj.mk.enableDragging() // 可拖拽
      obj.mk.addEventListener('dragend', function(e) { // 监听标注的拖拽，获取拖拽后的经纬度
        this.latitude = point.lat
        this.longitude =  point.lng
      })
      obj.map.panTo(point)
     
    },
    listChina(){
          listChina().then(res=>{
          this.options = res.data.map(rItem => {
                return {
                  value: rItem.id,
                  label: rItem.cityName,
                  children:rItem.children.map(item=>{
                    return {
                      value: item.id,
                      label: item.cityName,
                      children:item.children.map(stem=>{
                        return {
                        value: stem.id,
                        label: stem.cityName
                        }
                      })
                    }
                  })
                }
              })
        })
    },
    handleChange(){
      console.log(this.form.province,123);
     
    },
    blurDetail(){
      const geocoder = new BMap.Geocoder();
      geocoder.getPoint(this.form.detail, point => {
        if (point) {
          this.result = `经度：${point.lng}，纬度：${point.lat}`;
          console.log(this.result,123);
        } else {
          this.result = '地址解析失败';
          console.log(this.result,123);
        }
      }, '北京市');
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加门店";
    },
    // 上下架
    handleGround(row,statue) {
      const params = {
        id:row.id,
        statue:statue
      }
      this.$confirm(`此操作将${ statue ===1?'上架':'下架'}该数据, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateCase(params).then((res) => {
            this.$message({
            type: 'success',
            message: `${ statue ===1?'上架':'下架'}成功!`
          });
          this.getList()
          })
          
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消上下架'
          });          
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStore(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改门店";
      });
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handReset(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认重置编号为"' + ids + '"的数据项？').then(function() {
        return listResetPwd({userId:ids});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("重置成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delStore(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
